package class04;

public class Code04_K个节点的组内链表逆序 {

    //单链表节点
    public static class ListNode {
        public int value;
        public ListNode next;
    }

    //k个节点的尾节点
    public static ListNode getKGroupEnd(ListNode start, int k) {
        while (start != null && (--k != 0)) {
            start = start.next;
        }
        return start;
    }

    //k个节点的反转 到end.next结束
    public static void reverse(ListNode start, ListNode end) {
        end = end.next;
        ListNode pre = null;
        ListNode current = start;
        ListNode next = null;

        while (current != end) {
            next = current.next;
            current.next = pre;
            pre = current;
            current = next;
        }
        start.next = end;
    }

    //k个一组反转
    public static ListNode reverseKGroup(ListNode head, int k){
        ListNode start = head;
        ListNode end = getKGroupEnd(start, k);
        if (end == null) {
            return head;
        }
        // 第一组凑齐了！
        head = end;
        reverse(start, end);
        // 上一组的结尾节点
        ListNode lastEnd = start;
        while (lastEnd.next != null) {
            start = lastEnd.next;
            end = getKGroupEnd(start, k);
            if (end == null) {
                return head;
            }
            reverse(start, end);
            lastEnd.next = end;
            lastEnd = start;
        }
        return head;

    }
}
